package com.oss.service.impl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.oss.annotation.PreUpdateTime;
import com.oss.base.baseconst.ConfigConst;

public class OSSUploadService {
	@PreUpdateTime
	public void test(){
		
	}

	
	public void putObject() throws IOException{
		/*
         * Constructs a client instance with your account for accessing OSS
         */
        OSSClient client = new OSSClient(ConfigConst.ENDPOINT, ConfigConst.ACCESSKEYID, ConfigConst.ACCESSKEYSECRET);

        try {

            /**
             * Note that there are two ways of uploading an object to your bucket, the one 
             * by specifying an input stream as content source, the other by specifying a file.
             */

            /*
             * Upload an object to your bucket from an input stream
             */
            System.out.println("Uploading a new object to OSS from an input stream\n");
            String content = "Thank you for using Aliyun Object Storage Service";
            client.putObject(ConfigConst.BUCKETNAME, ConfigConst.KEY, new ByteArrayInputStream(content.getBytes()));

            /*
             * Upload an object to your bucket from a file
             */
            System.out.println("Uploading a new object to OSS from a file\n");
            File f =  createSampleFile();
            System.out.println("up file size:"+f.length());
            PutObjectRequest req = new PutObjectRequest(ConfigConst.BUCKETNAME, ConfigConst.KEY+f.getName(),f);
            req.addHeader("x-oss-object-acl", "private");
            client.putObject(req);
            
            /*
             * Download an object from your bucket
             */
            System.out.println("Downloading an object");
            OSSObject object = client.getObject(new GetObjectRequest(ConfigConst.BUCKETNAME, ConfigConst.KEY));
            System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
            System.out.println("down file size:"+object.getObjectContent().available());
            displayTextInputStream(object.getObjectContent());

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
            client.shutdown();
        }
	}
	
	public void putObjectBySingUrl() throws IOException{
		File f =  createSampleFile();
		URL url = new OssSignUrlService().getPutSignUrl(f.getName());
		System.out.println(url.toExternalForm());
		FileInputStream fin = new FileInputStream(f);
		OSSClient client = new OSSClient(ConfigConst.ENDPOINT, ConfigConst.ACCESSKEYID, ConfigConst.ACCESSKEYSECRET);
		
		// 添加PutObject请求头
		Map<String, String> customHeaders = new HashMap<String, String>();
		customHeaders.put("Content-Type", "application/octet-stream");
		// 添加user meta
		customHeaders.put("x-oss-meta-author", "aliy");
		
		PutObjectResult result = client.putObject(url, fin, f.length(), customHeaders);
		System.out.println(result.getETag());
		
	}
	
	public void simplePutByUrl() throws IOException, ParseException{
		File f =  createSampleFile();
		OSSClient client = new OSSClient(ConfigConst.ENDPOINT, ConfigConst.ACCESSKEYID, ConfigConst.ACCESSKEYSECRET);
		Date expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2016 14:20:00 GMT");
		URL url = client.generatePresignedUrl(ConfigConst.BUCKETNAME, ConfigConst.KEY+f.getName(), expiration,HttpMethod.PUT);
		PutObjectResult result = client.putObject(url, new FileInputStream(f) , f.length(),null);
		System.out.println(result.getETag());
	}
	
	
	public static File createSampleFile() throws IOException {
        File file = File.createTempFile("oss-java-sdk-", ".txt");
        file.deleteOnExit();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("abcdefghijklmnopqrstuvwxyz\n");
        writer.write("0123456789011234567890\n");
        writer.write("0123456789\n");
        writer.close();

        return file;
    }

    private static void displayTextInputStream(InputStream input) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;

            System.out.println("\t" + line);
        }
        System.out.println();

        reader.close();
    }
}
